package cn.snorlaxzjt.LBSserver.service;


import cn.snorlaxzjt.LBSserver.common.BusinessCode;
import cn.snorlaxzjt.LBSserver.common.Result;
import cn.snorlaxzjt.LBSserver.mapper.UserMapper;
import cn.snorlaxzjt.LBSserver.po.entity.User;
import cn.snorlaxzjt.LBSserver.security.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;


@Transactional(rollbackFor = RuntimeException.class)
@Slf4j
@Service
public class UserService {
    @Resource
    PasswordEncoder passwordEncoder;

    @Resource
    JwtTokenUtil jwtTokenUtil;

    @Resource
    UserMapper userMapper;

    private String avatarPath = "";
    /**
     * 注册
     * @param user 参数封装
     * @return Result
     */
    public User regist(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userMapper.insert(user);
        return user;
    }

    public List<User> getUserInfoByList(List<Integer> list){
        if(list == null || list.size()==0) return new ArrayList<>();
        return userMapper.selectBatchIds(list);
    }

    private UserDetails loadUserByEmail(String email) throws UsernameNotFoundException {
        User user = getUserByEmail(email);
        if (user == null) {
            throw new UsernameNotFoundException("");
        }
        return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), new LinkedList<>());
    }


    public String login(String email, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByEmail(email);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }

            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            User user = getUserByEmail(email);
            token = jwtTokenUtil.generateToken(user.getId());
        } catch (AuthenticationException e) {
            log.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    public Integer getCurrentUserId() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return Integer.valueOf(auth.getName());
    }

    public User getUserByEmail(String email) {
        List<User> users = userMapper.selectByMap(new HashMap<String,Object>() {
            {
                put("email", email);
            }
        });
        if (users == null || users.size() == 0) {
            return null;
        }
        return users.get(0);
    }

    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    public void updateAvatar(MultipartFile file) throws IOException {
//        String fileName = file.getOriginalFilename();
//        String suffixName = fileName.substring(fileName.lastIndexOf("."));
//        String trueName = UUID.randomUUID() + suffixName;
//        File dest = new File(avatarPath + trueName);
//        file.transferTo(dest);
//        userMapper.updateAvatar(trueName, getCurrentUserId());
    }


}
